package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.mapper.SysPermissionMapper;
import com.woniuxy.pojo.SysPermission;
import com.woniuxy.pojo.SysRole;
import com.woniuxy.pojo.SysRolePermission;
import com.woniuxy.pojo.SysRoleUser;
import com.woniuxy.pojo.dto.AddPermissionDTO;
import com.woniuxy.pojo.dto.PermissionTree;
import com.woniuxy.service.SysPermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【t_sys_permission】的数据库操作Service实现
* @createDate 2025-06-06 11:35:33
*/
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
    implements SysPermissionService {

    @Autowired
    SysPermissionMapper sysPermissionMapper;

    @Autowired
    SysRoleServiceImpl sysRoleService;

    @Autowired
    SysRolePermissionServiceImpl sysRolePermissionService;

    @Autowired
    SysRoleUserServiceImpl sysRoleUserService;

//    @Autowired
//    SysPermissionMapper sysPermissionMapper;

    //查询所有的权限并组织完整
    @Override
    public List<PermissionTree> getPermissionForest() {
        //1.获取到数据库中的所有的权限列表
        List<SysPermission> sysPermissions = sysPermissionMapper.selectList(null);

        //2.使用迭代的方式组织权限列表
        List<PermissionTree> forest = this.buildForest(sysPermissions);
        return forest;
    }

    /**
     * 构建权限树结构（多个根节点组成的树集合）- 使用 parentId → childrenMap 优化
     *
     * @param allPermissions 所有权限列表（扁平结构）
     * @return 构建好的权限树列表
     */
    public List<PermissionTree> buildForest(List<SysPermission> allPermissions) {
        // 1. 构建 nodeMap：id -> PermissionTree 节点
        Map<Integer, PermissionTree> nodeMap = new HashMap<>();

        // 2. 构建 childrenMap：parentId -> List<PermissionTree>（提前分组子节点）
        Map<Integer, List<PermissionTree>> childrenMap = new HashMap<>();

        for (SysPermission perm : allPermissions) {
            PermissionTree node = new PermissionTree();
            BeanUtils.copyProperties(perm, node);
            nodeMap.put(node.getId(), node);

            // 将当前节点归入其 parentId 对应的列表中
            Integer parentId = node.getParentId();
            childrenMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 3. 组织父子结构
        List<PermissionTree> forest = new ArrayList<>();

        for (PermissionTree node : nodeMap.values()) {
            Integer parentId = node.getParentId();
            if (parentId == null || parentId == 0) {
                forest.add(node); // 根节点
            } else {
                PermissionTree parent = nodeMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(node); // 添加子节点
                } else {
                    forest.add(node); // 容错：无父节点也作为根节点处理
                }
            }
        }

        // 4. 排序整个森林
        for (PermissionTree root : forest) {
            sortTree(root); // 递归排序每一层
        }

        return forest;
    }

    /**
     * 递归排序每个节点的子节点
     */
    private void sortTree(PermissionTree node) {
        if (node.getSort() == null) {
            node.setSort(0);
        }
        // null 安全排序（null 值排在最后）
        node.getChildren().sort(Comparator.comparing(
                PermissionTree::getSort,
                Comparator.nullsLast(Comparator.naturalOrder())
        ));

        for (PermissionTree child : node.getChildren()) {
            sortTree(child);
        }
    }

    //新增一级权限
    @Override
    public Boolean addLevel1Perm(AddPermissionDTO dto) {
        dto.setParentId(0);
        return sysPermissionMapper.insert(dto)>0;
    }

    //删除指定id的权限，并删除其子项

    @Override
    public Boolean deletePermission(Integer id) {
        //根据当前的id收集其子id
        List<Integer> idsToDelete = new ArrayList<>();
        collectChileIds(id,idsToDelete);

        //批量删除
        return this.removeByIds(idsToDelete);
    }
    /**
     * 递归收集所有子权限ID
     */
    public void collectChileIds(Integer parentId,List<Integer> ids){
        ids.add(parentId);

        List<SysPermission> children  = this.lambdaQuery()
                .eq(SysPermission::getParentId,parentId)
                .list();
        for (SysPermission child : children) {
            collectChileIds(child.getId(),ids);
        }
    }

    @Override
    public Boolean addNewPermission(Integer parentId, SysPermission permission) {
        permission.setParentId(parentId);
        return sysPermissionMapper.insert(permission)>0;
    }

    @Override
    public Boolean editPermission(Integer id, SysPermission permission) {
        SysPermission sysPermission = sysPermissionMapper.selectById(id);
        sysPermission.setPname(permission.getPname());
        sysPermission.setCode(permission.getCode());

        return sysPermissionMapper.updateById(sysPermission) > 0;
    }

    @Override
    public List<SysPermission> getPermissionsByUserId(Integer id) {
        //根据用户的id获取角色
        LambdaQueryWrapper<SysRoleUser> wrapper = Wrappers.lambdaQuery(SysRoleUser.class).eq(SysRoleUser::getUserId, id);
        SysRoleUser roleUser = sysRoleUserService.getOne(wrapper);
        if (roleUser == null) {
            return Collections.emptyList();
        }
        //根据角色id查询该角色下的所有的权限id
        List<SysRolePermission> allRolePermission = sysRolePermissionService.getAllPermission(roleUser.getRoleId());
        if (allRolePermission == null || allRolePermission.isEmpty()) {
            return Collections.emptyList();
        }
        //根据角色权限，的 id 获取 权限的信息

        List<Integer> permissionIds = allRolePermission.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());

        List<SysPermission> sysPermissions = this.listByIds(permissionIds);

        return sysPermissions;
    }
}




